<script setup lang="ts">
import { ref, nextTick } from 'vue'
import axios from 'axios'
import { Headset } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'

const chatItemList = ref([] as any)
const question = ref('')
const nowText = ref('')
const sending = ref(false)

const handleInputKeyDown = (event : any) => {
  if (event.keyCode === 13 && !event.shiftKey) {
    event.preventDefault() // 取消事件的默认换行动作
    event.cancelBubble = true // ie阻止冒泡行为
    event.stopPropagation() // Firefox阻止冒泡行为
    if (question.value !== '') {
      submitQuestion()
    }
  }
}

// submit question
const submitQuestion = async () => {
  sending.value = true
  chatItemList.value.push({
    message: question.value,
    role: 'user'
  })
  const message = await axios.post(`/api/chat`, {
      message: question.value
    },{ timeout: 10 * 60 * 1000 });

  const answer = {
    message: message.data,
    role: 'assistant',
    recommendation: ''
  };
  chatItemList.value.push(answer)
  sending.value = true
  question.value = ''
  doRecommendation(answer)
}

const doRecommendation = async (answer: any)=> {
  const _recommendation = await axios.post(`/api/recommendation`, {
    message: chatItemList.value
  },{ timeout: 10 * 60 * 1000 }) as any;
  answer.recommendation = _recommendation.data
  // 解决页面数据没有实时刷新
  nextTick(() => {
    answer.recommendation = answer.recommendation
    question.value = '  '
    question.value = ''
  });
}

const copyToClipboard = (content) => {
  nowText.value = content.replace(/<br>/g, '\n')
  nextTick(() => {
    const textElement = document.getElementById('chat-content-text')
    textElement?.select()
    if (document.execCommand('copy')) {
      ElMessage({
        message: '已复制到剪贴板',
        type: 'success',
      })
    }
  })
}

//2.语音播报
const speech = (data: string) => {
  window.speechSynthesis.speak(new SpeechSynthesisUtterance(data))
}

</script>

<template>
  <div class="chat-container">
    <div class="chat-item-wrapper">
      <!--欢迎语-->
      <div class="greeting" v-if="chatItemList.length === 0" >
        <div>您好！我是智能AI助理。</div>
        <div>您可以通过对话，向我提问。</div>
      </div>
      <div
        class="chat-item"
        v-for="(item, index) in chatItemList"
        :key="index">
        <div class="chat-item-avatar">
          <img v-if="item.role === 'user'" src="@/assets/images/chat-user.png" alt="user"/>
          <img v-else src="@/assets/images/chat-ai.png" alt="assistant"/>
        </div>
        <div :class="{'chat-item-text': true, 'chat-item-text-user' : item.role === 'user'}">
          <div class="chat-item-content">
            {{ item.message }}
          </div>
          <div v-if="item.role === 'assistant' && item.recommendation !== ''" class="chat-item-recommend">
            <div class="chat-item-recommend-title" style="display: flex;align-items: center">
              <el-button type="text">
                <el-icon><MagicStick /></el-icon>
              </el-button>
              <div style="background-color: #FFFFFF;font-size: 14px;padding: 0px 5px">智能推荐</div>
              <div style="width: 80%;height: 1px;background-color: #e8ebf0;"></div>
            </div>
            <div class="chat-recommend-items">
              <div class="recommend-item">
                <div v-html="marked(item.recommendation)">
                </div>
              </div>
            </div>
            <div class="chat-item-tools">
              <el-button type="text" @click="copyToClipboard(item.message)">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
              <el-button type="text" @click="speech(item.message)">
                <el-icon><Headset /></el-icon>
              </el-button>
            </div>
          </div>
          <div class="chat-item-tools">
          </div>
        </div>
      </div>
    </div>
    <div class="chat-question-wrapper">
      <div class="chat-input-wrapper">
        <el-input
          v-model="question"
          autosize
          type="textarea"
          :rows="2"
          :maxlength="5500"
          placeholder="在这里输入"
          style="font-size: 16px"
          @keydown.enter="handleInputKeyDown"
        >
        </el-input>
        <el-button
          :disabled="question.length === 0"
          class="question-submit-button"
          size="medium"
          type="primary"
          @click="submitQuestion">发送</el-button>
      </div>
    </div>
  </div>
  <!-- 用于复制回答的内容 -->
  <textarea id="chat-content-text" v-model="nowText" style="display: inline;height: 0px;width: 100%" rows="3"></textarea>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding-bottom: 10px;
}
.chat-item-wrapper {
  flex-grow: 1;
  padding: 10px 10% 0 10%;
  overflow: scroll;
  max-height: calc(100vh - 60px - 40px - 30px);
}
.recommend-item img {
  width: 100px !important;
  height: 150px !important;;
}
.chat-item {
  display: flex;
  flex-direction: row;
  margin-bottom: 15px;
}
.chat-item-avatar {
  width: 40px;
}
.chat-item-avatar img {
  width: 32px;
  height: 32px;
}
.chat-item-text {
  flex-grow: 1;
  margin-left: 10px;
  border-radius: 5px;
  box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
  padding: 5px;
}
.chat-item-text-user {
  box-shadow: none;
}
.greeting {
  width: 100%;
  text-align: center;
  margin-top: 5px
}
.greeting div:nth-child(1) {
  font-size: 20px;
  font-weight: bolder;
}
.greeting div:nth-child(2){
  font-size: 16px;
  line-height: 2em;
}
.chat-item-recommend {
  margin-top: 5px;
}
.chat-question-wrapper {
  padding: 5px;
  min-height: 50px;
  max-height: 200px;
  display: flex;
  justify-content: center; /* 水平居中 */
}

.chat-input-wrapper {
  width: 80%;
  background: #fff;
  border: 1px solid rgba(0,0,0,.08);
  border-radius: 16px;
  position: relative;
  overflow: hidden;
  max-height: 200px;
}
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
  resize: none;
  cursor: default;
  max-height: 200px;
  padding-right: 60px;
}
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 0;
}
:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 0;
}
.question-submit-button {
  position: absolute;
  right: 5px;
  bottom: 5px;
}
.chat-item-tools {
  float: right;
}
</style>